package com.atguigu.edu.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.util.MykafkaUtil;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

/**
 * @ClassName DwdTrafficHomeDetail
 * @Description TODO 首页浏览
 * @Author AFei
 * @Date 2022/9/5 23:36
 * @Version 1.0
 *      需要启动的进程
 *          zk kafka flume DwdTrafficBaseLogSplit DwdTrafficHomeDetail
 */
public class DwdTrafficHomeDetail {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);

        String topic = "dwd_traffic_page_log";
        String groupId = "dwd_traffic_home_detail_group";

        FlinkKafkaConsumer<String> kafkaConsumer = MykafkaUtil.getKafkaConsumer(topic, groupId);

        DataStreamSource<String> kafkaStrDS = env.addSource(kafkaConsumer);

        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.map(JSON::parseObject);

        KeyedStream<JSONObject, String> keyedDS = jsonObjDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));

        // TODO 过滤出首页浏览数据
        SingleOutputStreamOperator<JSONObject> filterDS = keyedDS.filter(
                new RichFilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        String lastPageId = jsonObj.getJSONObject("page").getString("last_page_id");
                        String pageId = jsonObj.getJSONObject("page").getString("page_id");
                        if (lastPageId == null && pageId.equals("home")) {
                            return true;
                        }
                        return false;
                    }
                }
        );
        // TODO 将首页浏览数据写到kafka主题中
        filterDS.print(">>>>>");
        filterDS.map(jsonObj -> jsonObj.toJSONString())
                .addSink(MykafkaUtil.getKafkaProducer("dwd_traffic_home_detail"));

        env.execute();
    }
}
